package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<BrandDTO> queryBrandByCategory(Long categoryId) {
        // 查询
        List<Brand> list = getBaseMapper().queryByCategoryId(categoryId);
        // 转换DTO
        return BrandDTO.convertEntityList(list);
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows) {
        // 0.健壮性判断
        page = Math.max(1, page);
        rows = Math.max(1, rows);
        // 判断是否有搜索关键字
        boolean isNotBlank = StringUtils.isNotBlank(key);
        // 1.分页查询 SELECT * FROM tb_brand b
        Page<Brand> result = query() // WHERE b.`name` LIKE "%x%"
                .like(isNotBlank, "name", key)
                .or() // OR	b.letter = "x"
                .eq(isNotBlank,"letter", key)
                // LIMIT	0, 5
                .page(new Page<>(page, rows));

        // 2.解析
        long total = result.getTotal();
        long totalPage = result.getPages();
        List<Brand> list = result.getRecords();

        // 3.封装PageDTO并返回
        return new PageDTO<>(total, totalPage, BrandDTO.convertEntityList(list));
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        // 1.新增品牌
        // 1.1.把DTO转为PO
        Brand brand = brandDTO.toEntity(Brand.class);
        // 1.2.新增品牌
        boolean success = save(brand);
        if (!success) {
            throw new LyException(500, "更新品牌失败！");
        }
        // 1.3.回显id
        Long brandId = brand.getId();

        // 2.中间表新增
        // 2.1.获取与品牌有关的所有分类id
        List<Long> categoryIds = brandDTO.getCategoryIds();
        // 2.2.把分类id与品牌id组合，封装为CategoryBrand
        List<CategoryBrand> categoryBrandList = categoryIds.stream()
                .map(categoryId -> CategoryBrand.of(categoryId, brandId)).collect(Collectors.toList());
        /*List<CategoryBrand> categoryBrands = new ArrayList<>(categoryIds.size());
        for (Long categoryId : categoryIds) {
            CategoryBrand categoryBrand = CategoryBrand.of(categoryId, brandId);
            categoryBrands.add(categoryBrand);
        }*/
        // 2.3.批量新增
       categoryBrandService.saveBatch(categoryBrandList);
    }
}